<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Upload Image</title>
</head>
<body>
  <h1>Upload an Image</h1>
  <input type="file" id="fileInput" accept="image/*">
  <button id="uploadBtn">Upload</button>

  <script>
    const backendCanisterId = "3l4c5-2qaaa-aaaab-qacpq-cai";
    const backendUrl = `https://${backendCanisterId}.icp0.io`;

    document.getElementById("uploadBtn").addEventListener("click", async () => {
      const fileInput = document.getElementById("fileInput");
      if (fileInput.files.length === 0) {
        alert("Please select a file.");
        return;
      }

      const file = fileInput.files[0];
      const arrayBuffer = await file.arrayBuffer(); // Convert file to ArrayBuffer
      const blob = new Uint8Array(arrayBuffer); // Convert to Uint8Array

      // Use `agent-js` to communicate with the backend
      const { HttpAgent, Actor, idlFactory } = require("@dfinity/agent");
      const agent = new HttpAgent({ host: backendUrl });

      // Replace with your backend's candid definition
      const canisterActor = Actor.createActor(idlFactory, {
        agent,
        canisterId: backendCanisterId,
      });

      try {
        const response = await canisterActor.upload(blob);
        console.log("Upload successful:", response);
        alert("Upload successful!");
      } catch (err) {
        console.error("Upload failed:", err);
        alert("Upload failed.");
      }
    });
  </script>
</body>
</html>
